const ws = require('ws')
const path = require('path')
const fileUtils = require('../utils/file_utils')

const wss = new ws.Server({
  port: 9998
})

module.exports.listen = () => {
  wss.on('connection', client => {
    console.log('有客户端连接了。。。')
    client.on('message', async msg => {
      console.log('客户端发送数据给服务端了: ' + msg)
      let payload = JSON.parse(msg)
      const action = payload.action
      if(action === 'getData') {
        let filePath = '../data/' + payload.chartName + '.json'
        filePath = path.join(__dirname, filePath)
        let data = await fileUtils.getFileJsonData(filePath)
        payload.data = data
        client.send(JSON.stringify(payload))
      }else {
        wss.clients.forEach(client => {
          // 我的环境这里的msg变成了buffer, 所以toSring转换一下
          client.send(msg.toString())
        })
      }
    })
  })
}